package com.dindang.checkline.mvp.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.dindang.checkline.di.component.DaggerScanComponent;
import com.dindang.checkline.di.module.ScanModule;
import com.dindang.checkline.mvp.greendao.entity.CheckPiont;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;

import com.dindang.checkline.mvp.contract.ScanContract;
import com.dindang.checkline.mvp.presenter.ScanPresenter;

import com.dindang.checkline.R;
import com.jess.arms.utils.LogUtils;


import cn.bingoogolapple.qrcode.core.BarcodeType;
import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zxing.ZXingView;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 03/07/2019 09:13
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class ScanActivity extends BaseActivity<ScanPresenter> implements ScanContract.View, QRCodeView.Delegate {
    TextView mTvTitle;
    RecyclerView mRecyclerView;
    ImageView mIvBack;
    ImageView mIvFlash;
    TextView mTvFlashTip;
    ZXingView mZXingView;
    private CheckPiont mData;
    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerScanComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .scanModule(new ScanModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_scan; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mIvBack = findViewById(R.id.maintenance_iv_back);
        mTvTitle =  findViewById(R.id.maintenance_tv_title);
        mRecyclerView = findViewById(R.id.recyclerView);
        mIvFlash = findViewById(R.id.ivFlash);
        mTvFlashTip = findViewById(R.id.tvFlashTip);
        mZXingView = findViewById(R.id.zxingview);
        mTvTitle.setText("二维码");
//        mTvTitle.setOnClickListener(v -> finish());
        mIvBack.setOnClickListener(v -> finish());
        mIvFlash.setOnClickListener(v -> openCloseFlash());
        mTvTitle.setOnClickListener(v -> gotoChoose());
        mZXingView.setDelegate(this);
        mZXingView.changeToScanQRCodeStyle(); // 切换成扫描二维码样式
        mZXingView.setType(BarcodeType.TWO_DIMENSION, null); // 只识别二维条码
//        mZXingView.setType(BarcodeType.ONLY_CODE_128, null); // 只识别 CODE_128
//        mZXingView.startSpotAndShowRect(); // 显示扫描框，并开始识别
        //去寻找是否已经有了相机的权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){
            //Toast.makeText(MainActivity.this,"您申请了动态权限",Toast.LENGTH_SHORT).show();
            //如果有了相机的权限有调用相机
            mZXingView.startCamera();

        }else {
            //否则去请求相机权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 100);
        }
        mZXingView.startSpotAndShowRect(); // 显示扫描框，并开始识别
    }

    public void gotoChoose() {
        LogUtils.debugInfo("zp","点击");
        Intent intent = new Intent(ScanActivity.this, ChooseItemActivity.class);
        intent.putExtra("data",getIntent().getStringExtra("data"));
        ScanActivity.this.startActivity(intent);
        this.finish();
    }

    @Override
    protected void onStop() {
        mZXingView.stopCamera(); // 关闭摄像头预览，并且隐藏扫描框
        super.onStop();
    }

    @Override
    protected void onStart() {
        super.onStart();

        mZXingView.startCamera(); // 打开后置摄像头开始预览，但是并未开始识别
//        mZXingView.startCamera(Camera.CameraInfo.CAMERA_FACING_FRONT); // 打开前置摄像头开始预览，但是并未开始识别

        mZXingView.startSpotAndShowRect(); // 显示扫描框，并开始识别
    }

    @Override
    protected void onDestroy() {
        mZXingView.onDestroy(); // 销毁二维码扫描控件
        super.onDestroy();
    }

    @Override
    public void onScanQRCodeSuccess(String result) {
        Log.i("zp", "result:" + result);
//        setTitle("扫描结果为：" + result);
        vibrate();
        mData = JSON.parseObject(getIntent().getStringExtra("data"),CheckPiont.class);
        if(result.substring(result.indexOf("=")).equals(mData.getLId())){
            gotoChoose();
        }

//        Intent resultIntent = new Intent();
//        Bundle bundle = new Bundle();
//        bundle.putInt(AppContant.RESULT_TYPE, AppContant.RESULT_SUCCESS);
//        bundle.putString(AppContant.RESULT_STRING, result);
//        resultIntent.putExtras(bundle);
//        setResult(RESULT_OK, resultIntent);
//        finish();
//        mZXingView.startSpot(); // 开始识别
    }

    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }

    @Override
    public void onCameraAmbientBrightnessChanged(boolean isDark) {
        // 这里是通过修改提示文案来展示环境是否过暗的状态，接入方也可以根据 isDark 的值来实现其他交互效果
        String tipText = mZXingView.getScanBoxView().getTipText();
        String ambientBrightnessTip = "\n环境过暗，请打开闪光灯";
        if (isDark) {
            if (!tipText.contains(ambientBrightnessTip)) {
                mZXingView.getScanBoxView().setTipText(tipText + ambientBrightnessTip);
            }
        } else {
            if (tipText.contains(ambientBrightnessTip)) {
                tipText = tipText.substring(0, tipText.indexOf(ambientBrightnessTip));
                mZXingView.getScanBoxView().setTipText(tipText);
            }
        }
    }

    @Override
    public void onScanQRCodeOpenCameraError() {
        Log.e("zp", "打开相机出错");
    }

    boolean isFlash = false;
    /**
     * 开启关闭闪光灯
     */
    public void openCloseFlash() {
        if(isFlash){
            isFlash = false;
            mZXingView.closeFlashlight(); // 关闭闪光灯
            mIvFlash.setImageResource(R.mipmap.ic_flash_close);
            mTvFlashTip.setText("打开闪光灯");
        }else{
            isFlash = true;
            mZXingView.openFlashlight(); // 打开闪光灯
            mIvFlash.setImageResource(R.mipmap.ic_flash_open);
            mTvFlashTip.setText("关闭闪光灯");
        }
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public TextView getTvTitle() {
        return mTvTitle;
    }

    @Override
    public ImageView getIvBack() {
        return mIvBack;
    }

    @Override
    public ImageView getIvFlash() {
        return mIvFlash;
    }

    @Override
    public TextView getTvFlashTip() {
        return mTvFlashTip;
    }

    @Override
    public ZXingView getZXingView() {
        return mZXingView;
    }

    @Override
    public BaseActivity getActivity() {
        return this;
    }
}
